package com.lengmou.service.impl;

import com.lengmou.dao.CarsDao;
import com.lengmou.entity.Cars;
import com.lengmou.service.CarsService;
import com.lengmou.util.TimeTool;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@Service("CarsService")
public class CarsServiceImpl implements CarsService {
    @Resource
    private CarsDao cd;
    @Override
    public List<Cars> getAll() {
        return cd.querysAll();
    }

    @Override
    public List<Cars> getCarsByUserId(int userid) {
        return cd.querysCarsByUserId(userid);
    }

    @Override
    public List<Cars> search(Map<String,Object> map) {

        return cd.search(map);
    }

    @Override
    public Cars getById(String id) {
        return cd.queryById(id);
    }

    @Override
    public int addCars(Cars cars) {
//        判读该用户购物车里有没有该商品，如果存在直接加数量
        Cars cars1 = existsCarGoods(cars);
        if(cars1!=null){
            cars1.setNum(cars1.getNum()+cars.getNum());
            return cd.updateCars(cars1);
        }else{
            cars.setId(UUID.randomUUID().toString());
            cars.setCreatetime(TimeTool.time());
            return cd.addCars(cars);
        }
    }

    @Override
    public int setCarsGoodsid(Cars cars) {
        Cars byId = getById(cars.getId());
        if(byId!=null){
            byId.setGoodsid(cars.getGoodsid());
            return cd.updateCars(byId);
        }
        return -1;
    }

    @Override
    public int setCarsNum(Cars cars) {
        Cars byId = getById(cars.getId());
        if(byId!=null){
            byId.setNum(cars.getNum());
            return cd.updateCars(byId);
        }
        return -1;
    }

    @Override
    public int setCarsUserid(Cars cars) {
        Cars byId = getById(cars.getId());
        if(byId!=null){
            byId.setUserid(cars.getUserid());
            return cd.updateCars(byId);
        }
        return -1;
    }

    @Override
    public Cars existsCarGoods(Cars cars) {
        if(cars!=null){
            List<Cars> carsByUserId = getCarsByUserId(cars.getUserid());
            for (Cars car:carsByUserId) {
                if(car.getGoodsid()==cars.getGoodsid()){
                    return car;
                }
            }
        }
        return null;
    }

    @Override
    public int deleteCars(String id) {
        Cars byId = getById(id);
        if(byId!=null){
            return cd.deleteCars(id);
        }
        return -1;
    }
}
